package com.cutthroatcreations.woodenrailway;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.util.Log;

public class LargeImageFragment extends Fragment {
	private static String TAG = "LargeImageFragemt";
	private View view;
	private int index;
	private int trainId;
	private ImageView largeImage;

	public LargeImageFragment() {
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle bundle = this.getArguments();
		index = bundle.getInt("index", 0);
		trainId = bundle.getInt("id", 1);
		Log.i(TAG, String.valueOf(index));
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Log.i(TAG, "CreateFrag");

		view = (View) inflater.inflate(R.layout.image_frag, container, false);

		largeImage = (ImageView) view.findViewById(R.id.imageLarge);

		largeImage.setScaleType(ScaleType.FIT_CENTER);
		AsyncTask<String, Void, Bitmap> loadImageTask = new loadList();
		loadImageTask.execute(String.valueOf(index));
		return view;
	}

	public class loadList extends AsyncTask<String, Void, Bitmap> {

		@Override
		protected void onPreExecute() {
			// progressDialog =
			// ProgressDialog.show(WoodenApplication.getContext(),
			// "LOADING IMAGE",
			// "Please Wait....", true);
		};

		@Override
		protected Bitmap doInBackground(String... params) {

			Train train = WoodenApplication.getTrainById(trainId);

			return decodeImage(train.getID(),
					train.images.get(Integer.parseInt(params[0])).image_name);

		}

		// decodes image and scales it to reduce memory consumption
		private Bitmap decodeImage(int id, String imageName) {
			String imgName = imageName.replace(")", "_");
			imgName = imgName.replace(" ", "%20");
			String imgUrl = CustomHttpClient.BASE_URL
					+ "image.php?width=600&height=600&image=img/" + id + "/"
					+ imgName;

			try {

				return BitmapFactory.decodeStream((InputStream) new URL(imgUrl)
						.getContent());

			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Bitmap bm) {

			super.onPostExecute(bm);
			largeImage.setImageBitmap(bm);
			// progressDialog.dismiss();
		}

	}

}
